package web

import (
	"gddgame.cc/galaxy/common"
	"gddgame.cc/galaxy/server/web"
	"gddgame.cc/galaxy/server/web/middleware"
	"gddgame.cc/galaxy/utils/def"

	"net/http"
)

var (
	SessionAuth = func(context web.Context) bool {
		var b string
		if err := context.Get("id", &b); err != nil {
			return false
		} else {
			return true
		}
	}
	DefaultAuthFail = func() error {
		return AuthException("授权失败")
	}
)

func SessionAuthMiddle(logger def.Logger, store def.Store, router web.Router, id string, field string, authList ...common.AuthHandler) (common.Auth, web.Handler) {
	authList = append(authList, SessionAuth)
	authMiddle := common.AuthMiddle(authList, func() error {
		return AuthException("未登录")
	})
	auth := SessionAuthHandler(logger, store, router, id, field)
	return auth, authMiddle
}

func SessionAuthHandler(logger def.Logger, store def.Store, router web.Router, id string, field string) common.Auth {
	auth := common.Auth{
		Id:    id,
		Field: field,
	}
	cookie := &http.Cookie{
		Name:     "gak",
		Path:     "/",
		HttpOnly: true,
		Secure:   false,
		MaxAge:   30 * 24 * 60 * 60 * 1000, //30 day in ms
	}
	// session k
	router.Use(middleware.SessionWrap(logger, cookie.Name, store, cookie))
	return auth
}

func MultiAuthMiddle(fail func() error, authList ...common.AuthHandler) web.Handler {
	authList = append(authList, SessionAuth)
	if fail == nil {
		fail = DefaultAuthFail
	}
	authMiddle := common.AuthMiddle(authList, fail)
	return authMiddle
}
